package com.uniqueyi.baselib.atybase.normal;

import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;

import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.uniqueyi.baselib.R;
import com.uniqueyi.baselib.baseInterface.RefreshListener;
import com.uniqueyi.baselib.utilsbase.Utils;
import com.uniqueyi.baselib.utilsbase.appmanager.AppManager;
import com.uniqueyi.baselib.utilsbase.log.LogUtil;

/**
 * Created by
 * author:  cwy.
 * date:    2018/3/2.  10:10.
 * prj:     Uniqueyi.
 */
public abstract class BaseAty extends AppCompatActivity implements View.OnClickListener {


    FrameLayout frg_content;
    AppBarLayout appbar;
    Toolbar toolbar;
    Toolbar toolbar_transparent;
    View loading_view;
    View load_retry_view;
    View custom_empty_view;
    private View childView;
    private RefreshListener refreshListener;
    Boolean translateFlag = false;

    public void setRetryRefreshItr(RefreshListener refreshListener) {
        this.refreshListener = refreshListener;
    }

    public String toolbarTitle = "";
    public boolean addBack = true;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 隐藏标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        try {
            WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
            Utils.ScreenWidth = wm.getDefaultDisplay().getWidth();
            Utils.ScreenHeight = wm.getDefaultDisplay().getHeight();

        } catch (Exception e) {
            e.printStackTrace();
        }
        //设置竖屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        // 添加Activity到堆栈
        AppManager.getInstance().addActivity(this);
        setContentView(R.layout.base_aty);

        initBaseView();
        initBaseToolbar();


        initView();
        initData();
        initEvent();


    }

    protected void initBaseToolbar(){
        toolbar.setTitle(toolbarTitle);
        setSupportActionBar(toolbar);
        setMenuClick();
    }

    protected  void setMenuClick(){
        if (getMenuResId() != 0)
            toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    onMenuClick(item);
                    return false;
                }
            });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        onMenu(item);
        if (item.getItemId() == android.R.id.home) {
            AppManager.getInstance().finishActivity(this);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (getMenuResId() != 0) {
            getMenuInflater().inflate(getMenuResId(), menu);
            return true;
        }
        return super.onCreateOptionsMenu(menu);
    }
    /**
     * 获取toolbar
     *
     * @return
     */
    public Toolbar getToolBar() {
        return toolbar;
    }

    public void setToolbarTitle(String toolbarTitle) {
        toolbar.setTitle(toolbarTitle);
    }

    private void addBack() {
        if (addBack) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }

    public void finshAty(){
        AppManager.getInstance().finishActivity(this);
    }

    protected  void initBaseView(){
        frg_content = (FrameLayout) findViewById(R.id.frg_content);
        appbar=findViewById(R.id.appbar);
        toolbar=findViewById(R.id.toolbar);
        toolbar_transparent=findViewById(R.id.toolbar_transparent);
        childView = View.inflate(this, getLayout(), null);
        frg_content.addView(childView);

        loading_view = View.inflate(this, R.layout.loading_view, null);
        load_retry_view = View.inflate(this, R.layout.load_retry_view, null);
        custom_empty_view = View.inflate(this, R.layout.custom_empty_view, null);

        loading_view.setVisibility(View.GONE);
        load_retry_view.setVisibility(View.GONE);

        load_retry_view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //重新读取数据
                hideReTry();
                if (refreshListener != null) {
                    refreshListener.reLoadData();
                }
            }
        });
    }

    public void showReTry() {
        load_retry_view.setVisibility(View.VISIBLE);
    }

    public void showLoading() {
        loading_view.setVisibility(View.VISIBLE);
    }

    public void hideReTry() {
        load_retry_view.setVisibility(View.GONE);
    }

    public void hideLoading() {
        loading_view.setVisibility(View.GONE);
    }

    public void hideTitle() {
        appbar.setVisibility(View.GONE);
    }

    public void hideTranslateTitle() {
        toolbar_transparent.setVisibility(View.GONE);
        translateFlag = false;
    }

    public void showTranslateTitle() {
        toolbar_transparent.setVisibility(View.VISIBLE);
        translateFlag = true;
    }

    public void showTitle() {
        appbar.setVisibility(View.VISIBLE);
    }

    //设置沉浸式
    public void setTranslateMode(View v, String title, final String color) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            //小于6.0不能设置沉浸式
            return;
        }

        showTranslateTitle();
        hideTitle();

        if (v instanceof XRecyclerView) {
            //
            final XRecyclerView rv = (XRecyclerView) v;

            final int[] starY = {0};
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    starY[0] = getScollYDistance(rv);
                    //LogUtil.getInstance().info("starY" + starY[0]);
                }
            }, 1000);
            //int starY=getScollYDis
            // tance(rv);


            rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                }

                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    if (!translateFlag) {
                        return;
                    }
                    LogUtil.getLogUtil().log("baseaty","setTranslateMode---高度" + getScollYDistance(recyclerView));
                    String alpha = "00";
                    int alphaNum = 0;
                    int num = getScollYDistance(recyclerView) - starY[0];
                    if (num < 0) {
                        num = 0;
                    }

                    if (starY[0] != 0) {
                        if (num >= starY[0]) {
                            alphaNum = 255;
                        } else {
                            alphaNum = num * 255 / starY[0];
                        }

                        if (alphaNum > 150) {
//                            custom_title_transparent.img_right_icon_2.setImageResource(R.drawable.more_black);
//                            custom_title_transparent.img_back.setImageResource(R.drawable.back_black);
//                            SetMyTitle_Translate(topTilte);
                            //custom_title_transparent.divide.setVisibility(View.VISIBLE);
                        } else {
//                            custom_title_transparent.img_right_icon_2.setImageResource(R.drawable.more_white);
//                            custom_title_transparent.img_back.setImageResource(R.drawable.back_white);
//                            SetMyTitle_Translate("");
                            //custom_title_transparent.divide.setVisibility(View.GONE);
                        }

                    } else {
                        alphaNum = 0;
                    }
                    alpha = Integer.toHexString(alphaNum);
                    if (alpha.length() == 1) {
                        alpha = "0" + alpha;
                    }
                    try {
                        toolbar_transparent.setBackgroundColor(Color.parseColor("#" + alpha + color));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            });
        }
    }

    public int getScollYDistance(RecyclerView recyclerView) {
        try{
            LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
            int position = layoutManager.findFirstVisibleItemPosition();
            //LogUtil.getInstance().info("第一个可见position:" + position);
            if (position <= 1) {
                View firstVisiableChildView = layoutManager.findViewByPosition(position);
                int itemHeight = firstVisiableChildView.getHeight();
                return (position) * itemHeight - firstVisiableChildView.getTop();
            } else {
                return 9999;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 结束Activity&从堆栈中移除
        AppManager.getInstance().finishActivity(this);
    }

    public abstract int getLayout();
    public abstract void initView();
    public abstract void initData();
    public abstract void initEvent();

    protected abstract void onMenuClick(MenuItem item);
    protected abstract boolean onMenu(MenuItem item);
    protected abstract int getMenuResId();
}